import pathlib
from uuid import UUID

from fastapi import APIRouter, Depends, Form, UploadFile, File


from core.database import get_db
from core.exceptions import (
    InternalServerException,
    NotFoundException,
    BadRequestException,
)
from service.tender_service import TenderService
from service.bid_service import BidService
from schema.all import (
    TendersGETResponse,
    TendersPOSTResponse,
    TendersBidsGETResponse,
    TendersBidsPOSTResponse,
    DELETEResponse,
    BidInfo,
    TenderInfo,
)

router = APIRouter()


@router.get(
    path="/",
    summary="获取所有招标记录",
    response_model=TendersGETResponse,
)
async def get_all_tender_records(db=Depends(get_db)):
    try:
        service = TenderService(db)
        tender_info_list = await service.list_tenders()
        tenders = []
        for info in tender_info_list:
            tender = TenderInfo(
                id=UUID(info.id),
                category=info.category,
                quarter=info.quarter,
            )
            tenders.append(tender)
        return TendersGETResponse(tenders=tenders)
    except Exception as e:
        raise InternalServerException(f"获取招标记录失败: {str(e)}")


@router.post(
    path="/",
    summary="创建招标记录",
    response_model=TendersPOSTResponse
)
async def create_tender_record(
    category: str = Form(...),
    quarter: str = Form(...),
    document: UploadFile = File(...),
    db=Depends(get_db),
):
    try:
        if not category or not quarter:
            raise BadRequestException("category 和 quarter 不能为空")

        service = TenderService(db)
        tender_id = await service.create_tender(category, quarter, document)
        tender = TenderInfo(
            id=tender_id,
            category=category,
            quarter=quarter,
        )
        return TendersPOSTResponse(tender=tender)
    except ValueError as e:
        raise BadRequestException(f"参数错误: {str(e)}")
    except Exception as e:
        raise InternalServerException(f"创建招标记录失败: {str(e)}")


@router.delete(
    path="/{tender_id}",
    summary="删除招标记录",
    response_model=DELETEResponse
)
async def delete_tender_record(
    tender_id: UUID,
    db=Depends(get_db),
):
    try:
        service = TenderService(db)
        deleted = await service.delete_tender(tender_id)
        if not deleted:
            raise NotFoundException("招标记录不存在或已被删除")
        return DELETEResponse(message="删除成功")
    except Exception as e:
        raise InternalServerException(f"删除招标记录失败: {str(e)}")

@router.get(
    path="/{tender_id}/bids",
    summary="获取指定招标记录的所有投标信息。",
    response_model=TendersBidsGETResponse
)
async def get_bids_for_tender(
    tender_id: UUID,
    db=Depends(get_db),
):
    try:
        service = BidService(db)
        bid_file_info_list = await service.get_info_by_tender_id(tender_id)
        bids = []
        for info in bid_file_info_list:
            bid = BidInfo(
                id=UUID(info.id),
                name=info.name,
                has_bargaining=info.bargaining,
            )
            bids.append(bid)
        return TendersBidsGETResponse(bids=bids)
    except NotFoundException as e:
        raise NotFoundException(f"招标记录不存在: {str(e)}")
    except Exception as e:
        raise InternalServerException(f"获取投标信息失败: {str(e)}")


@router.post(
    path="/{tender_id}/bids/sea",
    summary="上传一次海运投标文件",
)
async def create_sea_bid_for_tender(
    tender_id: UUID,
    starting_port: str = Form(...),
    file: UploadFile = File(...),
    db=Depends(get_db),
):
    service = BidService(db)
    if starting_port == "Shanghai":
        file.filename = f"(上海起){file.filename}"
    elif starting_port == "Jiujiang":
        file.filename = f"(九江起){file.filename}"
    bid_ids = await service.create_bids(tender_id, [file])
    bid = BidInfo(
        id=bid_ids[0],
        name=pathlib.Path(file.filename).stem,
        has_bargaining=False,
    )
    return TendersBidsPOSTResponse(bid=bid)


@router.post(
    path="/{tender_id}/bids/pipe",
    summary="上传一次管件投标文件",
)
async def create_pipe_bid_for_tender(
    tender_id: UUID,
    file: UploadFile = File(...),
    db=Depends(get_db)
):
    service = BidService(db)
    bid_ids = await service.create_bids(tender_id, [file])
    return {"message": f"已成功上传一份PP管件投标表。", "bid_ids": bid_ids}

@router.post(
    path="/{tender_id}/bids/electrical",
    summary="上传一次电气投标文件",
    response_model=TendersBidsPOSTResponse
)
async def create_electrical_bid_for_tender(
    tender_id: UUID,
    file: UploadFile = File(...),
    db=Depends(get_db),
):
    try:
        service = BidService(db)
        bid_ids = await service.create_bids(tender_id, [file])
        bid = BidInfo(
            id=bid_ids[0],
            name=pathlib.Path(file.filename).stem,
            has_bargaining=False,
        )
        return TendersBidsPOSTResponse(bid=bid)
    except NotFoundException as e:
        raise NotFoundException(f"招标记录不存在: {str(e)}")
    except ValueError as e:
        raise BadRequestException(f"参数错误: {str(e)}")
    except Exception as e:
        raise InternalServerException(f"创建投标记录失败: {str(e)}")

@router.post(
    path="/{tender_id}/bids/steel",
    summary="上传一次钢材投标文件",
    response_model=TendersBidsPOSTResponse
)
async def create_steel_bid_for_tender(
    tender_id: UUID,
    file: UploadFile = File(...),
    db=Depends(get_db),
):
    try:
        service = BidService(db)
        bid_ids = await service.create_bids(tender_id, [file])
        if not bid_ids:
            raise NotFoundException("投标记录不存在或未成功创建")
        bid = BidInfo(
            id=bid_ids[0],
            name=pathlib.Path(file.filename).stem,
            has_bargaining=False,
        )
        return TendersBidsPOSTResponse(bid=bid)
    except NotFoundException as e:
        raise NotFoundException(f"招标记录或投标记录不存在: {str(e)}")
    except ValueError as e:
        raise BadRequestException(f"参数错误: {str(e)}")
    except Exception as e:
        raise InternalServerException(f"创建投标记录失败: {str(e)}")